package com.leaves.config;

import cn.dev33.satoken.stp.StpInterface;
import com.leaves.common.publicmethod.methods.UserInfoDeal;
import com.leaves.entity.AuthInfo;
import com.leaves.entity.RoleInfo;
import com.leaves.entity.UserInfo;
import com.leaves.service.AuthInfoService;
import com.leaves.service.RoleInfoService;
import com.leaves.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2022年06月06日  14时35分24秒
 * @Description: 自定义权限验证接口扩展
 */
@Component    // 保证此类被SpringBoot扫描，完成Sa-Token的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {
    private static final Logger logger = LoggerFactory.getLogger(StpInterfaceImpl.class);
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private RoleInfoService roleInfoService;
    @Resource
    private AuthInfoService authInfoService;
    @Resource
    private UserInfoDeal userInfoDeal;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        logger.info("---------- 添加权限 -----------");
        List<String> list = new ArrayList<String>();
        UserInfo userInfo = userInfoService.getById(loginId.toString());
//        List<String> roleIdList = JSON.parseArray(userInfo.getRoleId(), String.class);
        List<String> roleIdList = userInfoDeal.getRoleIdListByUserId(userInfo.getId());
        List<RoleInfo> roleInfoList = roleInfoService.listByIds(roleIdList);
        roleInfoList.forEach(roleInfo -> {
//            List<String> authIdList = JSON.parseArray(roleInfo.getAuthId(), String.class);
            List<String> authIdList = userInfoDeal.getAuthIdListByRoleId(roleInfo.getId());
            List<AuthInfo> authInfoList = authInfoService.listByIds(authIdList);
            authInfoList.forEach(authInfo -> {
                list.add(roleInfo.getRoleIdentify() + "-" + authInfo.getAuthIdentify());
                System.out.println("权限：" + roleInfo.getRoleIdentify() + "-" + authInfo.getAuthIdentify());
            });
        });
        return list;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        logger.info("---------- 添加角色 -----------");
        List<String> list = new ArrayList<String>();
        UserInfo userInfo = userInfoService.getById(loginId.toString());
//        List<String> roleIdList = JSON.parseArray(userInfo.getRoleId(), String.class);
        List<String> roleIdList = userInfoDeal.getRoleIdListByUserId(userInfo.getId());
        List<RoleInfo> roleInfoList = roleInfoService.listByIds(roleIdList);
        roleInfoList.forEach(roleInfo -> {
            list.add(roleInfo.getRoleIdentify());
            System.out.println("角色：" + roleInfo.getRoleIdentify());
        });
        return list;
    }
}
